from flask import Flask, render_template_string
from flask_cors import CORS
from src.api import create_api_blueprint
from src.database.manager import DBManager
from src.utils.swagger_auto_config import SwaggerAutoConfig
from src.utils.logger import setup_flask_error_handlers

def create_app():
    app = Flask(__name__)
    
    # 设置全局错误处理
    setup_flask_error_handlers(app)
    
    # 配置跨域白名单
    cors_origins = ['*']
    
    # 配置 CORS
    CORS(app, resources={
        r"*": {
            "origins": cors_origins,
            "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
            "allow_headers": ["Content-Type", "Authorization"]
        }
    })
    
    # 配置应用
    app.config.from_object('src.config')
    
    # 初始化数据库
    db_manager = DBManager()
    db_manager.init_db()
    
    # 注册API蓝图
    api_blueprint = create_api_blueprint()
    app.register_blueprint(api_blueprint, url_prefix='/api')
    
    # 初始化Swagger自动配置
    SwaggerAutoConfig(app)
    
    return app

app = create_app()